package edu.neusoft.springmvc.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import edu.neusoft.springmvc.model.TestModel;

@Controller
@RequestMapping("/view")
public class TestViewController {

  @RequestMapping("/fm")
  public ModelAndView testFM() {
    ModelAndView mv = new ModelAndView();
    mv.addObject("hello", "hello world");
    mv.setViewName("freemarker");
    return mv;
  }

  @RequestMapping("/htmlview")
  public void htmlview(PrintWriter writer) {

    StringBuffer sb = new StringBuffer();
    sb.append("<!doctype html>");
    sb.append("<html>");
    sb.append("<head><title>this is a new page</title></head>");
    sb.append("<body><p>hello world</p></body>");
    sb.append("</html>");

    writer.write(sb.toString());

  }

  @ModelAttribute("testModel")
  public TestModel getTestModel() {
    return new TestModel("111", "222", "333", "444");
  }

  @RequestMapping("/jsonview")
  public void JsonView(ModelMap modelmap, PrintWriter writer) {
    TestModel model = (TestModel) modelmap.get("testModel");
    Map<String, Object> map = new HashMap<String, Object>();
    if (model != null) {
      map.put("result", "ok");
      map.put("data", model);
    }
    writer.write(JSON.toJSONString(map));
  }

  @RequestMapping("/jacksonView")
  @ResponseBody
  public Map<String, Object> jacksonView(ModelMap modelmap) {
    TestModel model = (TestModel) modelmap.get("testModel");
    Map<String, Object> map = new HashMap<String, Object>();
    if (model != null) {
      map.put("result", "ok");
      map.put("data", model);
    }

    return map;
  }
}
